<template>
  <el-dialog
    v-model="centerDialogVisible"
    title="添加商品信息"
    width="40%"
    center
    @close="closeDialog(false)"
  >
    <el-form
      ref="validateForm"
      :model="productForm"
      :rules="rules"
      label-width="80px"
      :status-icon="true"
    >
      <el-form-item label="商品名称" prop="name">
        <el-input v-model="productForm.name"></el-input>
      </el-form-item>
      <el-form-item label="商品型号" prop="code">
        <el-input v-model="productForm.code"></el-input>
      </el-form-item>
      <el-form-item label="商品单位" prop="unitName">
        <el-input v-model="productForm.unitName"></el-input>
      </el-form-item>
       <el-form-item label="商品税率" prop="taxRate">
        <el-input v-model="productForm.taxRate"></el-input>%
      </el-form-item>
      <el-form-item label="分类" prop="categoryId">
        <el-select
          v-model="productForm.categoryId"
          filterable
          placeholder="请选择"
        >
          <el-option
            v-for="item in categories"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          >
          </el-option>
        </el-select>
        <el-popover v-model:visible="visible" placement="top" :width="160">
          <p><el-input v-model="categoryName" placeholder="商品分类名称" /></p>
          <div style="text-align: right; margin: 0">
            <el-button size="mini" type="text" @click="closeCategory"
              >取消</el-button
            >
            <el-button type="primary" size="mini" @click="saveCategory"
              >保存</el-button
            >
          </div>
          <template #reference>
            <el-button size="mini" @click="visible = true">添加</el-button>
          </template>
        </el-popover>
      </el-form-item>
      <el-form-item label="幅宽" prop="specs">
        <el-select
          v-model="specSelect"
          multiple
          filterable
          allow-create
          default-first-option
          placeholder="选择幅宽"
        >
          <el-option
            v-for="item in specs"
            :key="item.name"
            :label="item.name"
            :value="item.name"
          >
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="价格" prop="price">
        <el-input v-model="productForm.price"></el-input>
      </el-form-item>
      <el-form-item label="商品图片" prop="coverImg">
        <el-upload
          class="avatar-uploader"
          action="/api/system/upload/file"
          :show-file-list="false"
          :on-success="handleAvatarSuccess"
          :before-upload="handleBeforeUpload"
          :headers="headers"
        >
          <img v-if="productImageUrl" :src="productImageUrl" class="avatar" />
          <i v-else class="el-icon-plus avatar-uploader-icon"></i>
        </el-upload>
      </el-form-item>
      <el-form-item label="详情内容">
        <WanEditorVue @setRemark="setRemark" />
      </el-form-item>

      <el-form-item>
        <el-button type="primary" @click="submitForm">保存</el-button>
         <el-button @click="() => {  closeDialog(false); } ">取消</el-button>
      </el-form-item>
    </el-form>
  </el-dialog>
</template>

<script>
import { reactive, ref, toRefs, onMounted, computed } from "vue";
import { ElMessage } from "element-plus";
import { postRequest, getRequest, hasEmoji } from "../../utils/api";
import WanEditorVue from "./WanEditor.vue";

function productAdd(state, validateForm, emit) {
  const submitForm = () => {
    validateForm.value.validate((valid) => {
      if (valid) {
      
        if (
          hasEmoji(state.productForm.name) ||
          hasEmoji(state.productForm.code)
        ) {
          ElMessage.error("不要输入表情包，再输入就打死你个龟孙儿~");
          return;
        }
        postRequest("/product/basic/list", state.productForm).then((res) => {
          if (res && res.code == 200) {
            const d = res.data;
            validateForm.value.resetFields();
            state.imageUrl = "";

            emit("onCloseDialog", false, d);
          } else {
            ElMessage({
              showClose: true,
              message: `${res.message}`,
              type: "error",
            });
          }
        });
      }
    });
  };
  return { submitForm };
}
function loadCategory(state) {
  getRequest("/product/category/list").then((res) => {
    if (res && res.code == 200) {
      state.categories = res.data;
    } else {
      ElMessage({ showClose: true, message: `查询失败`, type: "error" });
    }
  });
}

function useCategory(state) {
  const saveCategory = () => {
    postRequest("/product/category/", {
      name: state.categoryName,
      enabled: true,
    }).then((res) => {
      if (res.code == 200 && res.data) {
        state.categories.push(res.data);
        state.productForm.categoryId = res.data.id;
        state.categoryName = "";

        ElMessage({ showClose: true, message: res.message, type: "success" });
      }
    });

    state.visible = false;
  };

  const closeCategory = () => {
    state.categoryName = "";
    state.visible = false;
  };

  return { saveCategory, closeCategory };
}

const useSetRemark = (state) => {
  const setRemark = (content) => {
    state.productForm.proddesc = content;
  };
  return { setRemark };
};

export default {
  components: { WanEditorVue },
  props: {
    centerDialogVisible: Boolean,
  },
  emits: ["onCloseDialog"],
  setup(props, { emit }) {
    const validateForm = ref();
    const state = reactive({
      categoryName: "",
      visible: false,
      centerDialogVisible: props.centerDialogVisible,
      categories: [],
      specs: [
        { name: "2.5米" },
        { name: "3米" },
        { name: "3.5米" },
        { name: "可定制" },
      ],
      productImageUrl: "",
      headers: { Authorization: window.sessionStorage.getItem("tokenStr") },
      specSelect:[],
      productForm: {
        name: "",
        code: "",
        price: 0,
        spec: computed(()=>{return state.specSelect.toString()}),
        imageUrl: "",
        proddesc: "",
        enabled: true,
        categoryId: null,
        unitName:'',
        taxRate:13
      },
    });
    onMounted(() => {
      loadCategory(state);
    });

    const rules = {
      name: [{ required: true, message: "请输入商品名称", trigger: "blur" }],
      code: [{ required: true, message: "请输入型号", trigger: "blur" }],
      unitName: [{ required: true, message: "请输入商品单位", trigger: "blur" }],
       taxRate: [{ required: true, message: "请输入商品税率", trigger: "blur" }],
      
    };

    const closeDialog = (visible, data) => {
      validateForm.value.resetFields();
      emit("onCloseDialog", visible, data);
    };

    //图片上传
    const handleAvatarSuccess = (res) => {
      state.productForm.imageUrl = res.data;
      state.productImageUrl = res.data;
    };

    const handleBeforeUpload = (file) => {
      
      const name = file.name.split(".")[1];
      if (!["jpg", "jpeg", "png"].includes(name)) {
        ElMessage({
          showClose: true,
          message: "请上传jpg,jpeg,png对应的图片文件",
          type: "error",
        });
        return false;
      }

      return true;
    };
    return {
      ...toRefs(state),
      ...useCategory(state),
      closeDialog,
      rules,
      ...productAdd(state, validateForm, emit), //解构goodsAdd返回的结果  返回submitAdd对象函数 需要把富文本编辑器也传过去 这里省略了
      validateForm,
      handleBeforeUpload,
      handleAvatarSuccess,
      ...useSetRemark(state),
    };
  },
};
</script>

<style>
.el-form-item__error {
  padding-top: 0px;
}
.el-input__inner {
  height: 32px;
  line-height: 32px;
}
.el-form-item {
  margin-bottom: 10px;
}
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 18px;
  color: #8c939d;
  width: 88px;
  height: 88px;
  line-height: 88px;
  text-align: center;
}
.avatar {
  width: 88px;
  height: 88px;
  display: block;
}
</style>